package com.jianyun.jyzs.dao;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.QueryBuilder;
import com.jianyun.jyzs.bean.EnterInfo;
import com.jianyun.jyzs.db.DatabaseHelper;
import com.jianyun.jyzs.utils.LoginCache;


import java.sql.SQLException;
import java.util.List;

import com.jianyun.jyzs.utils.RceLog;


/**
 * Created by liml on 17/6/21.
 */

public class LoginDao {
    private Dao<EnterInfo, Integer> loginDao;
    private DatabaseHelper helper;

    public LoginDao(Context context) {
        try {
            helper = DatabaseHelper.getHelper(context);
            loginDao = helper.getDao(EnterInfo.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public List<EnterInfo> getListData() {
        try {
            QueryBuilder<EnterInfo, Integer> builder = loginDao.queryBuilder();
            return builder.query();
        } catch (Exception e) {
            return null;
        }


    }

    //true 存在
    public boolean getEnterInfo(EnterInfo enterInfo) {
        try {
            EnterInfo info = loginDao.queryBuilder().where().eq("enterinfo", enterInfo.getEnterinfo()).and().eq("account", enterInfo.getAccount()).queryForFirst();
            if (info == null) {
                RceLog.d("lml", info.toString());
                Integer autoId = info.getAutoId();
                Log.i("test", "可以：" + autoId);
                return false;
            } else {
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    //true 存在
    public int getEnterInfoID(EnterInfo enterInfo) {
        try {
            EnterInfo info = loginDao.queryBuilder().where().eq("enterinfo", enterInfo.getEnterinfo()).and().eq("account", enterInfo.getAccount()).queryForFirst();

            if (info == null) {
                return -1;
            } else {
                return info.getAutoId();
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -1;
        }
    }

    public synchronized void insert(EnterInfo enterInfo) {
        try {
            if (!getEnterInfo(enterInfo)) {
                loginDao.createIfNotExists(enterInfo);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    public void update(EnterInfo enterInfo) {
        try {
            int update = loginDao.update(enterInfo);
            Log.i("test", "数据：" + update);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }


    public void delEnter(EnterInfo enter) {
        try {
            loginDao.delete(enter);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
